package com.changgou.order.timetask;

import com.changgou.order.feign.PayFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.OrderService;
import com.changgou.util.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/8 0:34
 * @Version 1.0
 */
@Component
public class OrderTimerTask {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayFeign payFeign;

    /**
     * 定时任务:
     *  要求:
     *  1.每30秒检查一次redis中是否存在订单的数据
     *  2.如果有订单的数据检查订单的支付状态
     *  3.订单如果已经支付了,将订单信息从redis移除,更新数据库中订单的信息
     *  4.订单如果支付失败,将订单的信息从redis移除,删除(逻辑删除)数据库中的订单的信息
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void timerTask() {
        System.out.println("检查redis中订单是否支付成功定时任务开始..........");
        //获取redis中的所有数据
        List<Order> orderList = redisTemplate.boundHashOps("Order").values();
        //有数据,开始处理
        if (orderList != null) {
            for (Order order : orderList) {
                //获取orderId
                String orderId = order.getId();
                //远程调用查询当前支付状态
                Map dataMap = (Map) payFeign.queryStatus(orderId).getData();
                //若请求成功
                if ("SUCCESS".equalsIgnoreCase(dataMap.get("return_code").toString())) {
                    //获取交易状态
                    Object tradeStateObj = dataMap.get("trade_state");
                    if (tradeStateObj != null) {
                        String tradeState = tradeStateObj.toString();
                        if ("SUCCESS".equalsIgnoreCase(tradeState)) {
                            //支付成功
                            System.out.println("订单: "+orderId+" 支付成功........");

                            //获取微信交易流水号 transaction_id
                            String transactionId = dataMap.get("transaction_id").toString();
                            //代表支付成功 == 修改订单状态  写入数据库  删除redis缓存中的数据
                            orderService.updateStatus(orderId, transactionId);
                        } else if ("NOTPAY".equalsIgnoreCase(tradeState)) {
                            //未支付
                            System.out.println("订单: "+orderId+" 等待支付........");
                        } else {
                            System.out.println("订单: "+orderId+" 支付失败........");
                            //支付失败 修改订单状态为支付失败 redis中删除
                            orderService.deleteOrder(orderId);
                        }
                    }
                }
            }
        }
        System.out.println("================定时任务结束================");
    }
}
